﻿using ArticleUploadBatch.WinUI.Configs;
using ArticleUploadBatch.WinUI.Services;
using Common.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ArticleUploadBatch.WinUI.UserControls
{
    public partial class UcDayuArticleUpload : UserControl
    {
        public UcDayuArticleUpload()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 输出日志
        /// </summary>
        /// <param name="str"></param>
        void writeLineLog(string str)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    txtLog.Text += str + "\r\n";
                }));
            }
            else
            {
                txtLog.Text += str + "\r\n";
            }           
        }

        /// <summary>
        /// 更新文件列表
        /// </summary>
        private void refreshFileList()
        {
            string ext=combExtension.Text.Trim();

            string[] fileList = Directory.GetFiles(txtDir.Text, ext);
            List<string> fileTitles = new List<string>();
            foreach (var file in fileList)
            {
                fileTitles.Add(Path.GetFileNameWithoutExtension(file));
            }
            lstbFiles.DataSource = fileTitles;
        }

        //以下为事件处理方法--------------------------------------------------------------

        private void UcDayuArticleUpload_Load(object sender, EventArgs e)
        {
            //string[] exts = ConfigurationManager.AppSettings["UploadArticleFileExts"].ToString().Split('|');
            string[] exts = AppConfigXml.GetAppSettingValue("UploadArticleFileExts").ToString().Split('|');
            combExtension.Items.Clear();
            combExtension.Items.AddRange(exts);
            combExtension.SelectedIndex = 0;
            if (string.IsNullOrEmpty(txtDir.Text.Trim()))
            {
                txtDir.Text = Environment.CurrentDirectory.ToString();
            }
            refreshFileList();
            
        }
        private void btnDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog browserDialog = new FolderBrowserDialog();
            browserDialog.SelectedPath = txtDir.Text;
            if (browserDialog.ShowDialog() == DialogResult.OK)
            {
                txtDir.Text = browserDialog.SelectedPath;
                refreshFileList();
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {

                string ext = combExtension.Text.Trim();
                string userName = txtUserName.Text;
                string pwd = txtPwd.Text;
                string fileDir = txtDir.Text;
                if (!Directory.Exists(fileDir)) return;
                //获取所有文章路径
                string[] filePathList = Directory.GetFiles(fileDir, ext);
                if (filePathList.Length == 0)
                {
                    MessageBox.Show("当前目录中没有文章");
                    return;
                }

                
                Task.Run(() =>
                {
                    //大鱼号上传文章
                    DayuArticleService articleService = new DayuArticleService(userName, pwd);
                    articleService.UploadMany(filePathList, writeLineLog);

                    string sourceDir = txtDir.Text.Trim();
                    string destDir = Path.Combine(Environment.CurrentDirectory, "已上传/Dayu");
                    if (cbClearSourceDir.Checked && Directory.Exists(sourceDir))
                    {
                        if (!Directory.Exists(destDir))
                        {
                            Directory.CreateDirectory(destDir);
                        }
                        //Directory.Move(sourceDir, Path.Combine(destDir, Path.GetFileName(sourceDir)));
                        string[] files = Directory.GetFiles(sourceDir);
                        //复制已经上传的文件到已上传目录
                        foreach (string file in files)
                        {
                            string fileName = Path.GetFileName(file);
                            string destFile = Path.Combine(destDir, fileName);
                            File.Copy(file, destFile, true);
                        }
                        //删除原目录
                        Directory.Delete(sourceDir, true);
                    }
                    articleService.Quit();
                    MessageBox.Show("文章已经全部上传完成");
                });
            }
            catch (Exception err)
            {
                Log4Helper.Error(err);
                throw err;
            }
            


        }

        
    }
}
